
import requests
import json

group_id = "meetfacev2"

def get_access_token():
    
    client_id = "PzwMzPDzTLJftRuKlNg7FI9W"
    client_secret = "4jU9ZSrSftr0mSgncGc6Yfrph9NhdOGL"
        
    url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}"
    
    payload = ""
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    
    token = json.loads(response.text)['access_token']
    return token
    
def face_register(img64code, uid, userinfo):
    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add"

    params = {
        "image":img64code,
        "image_type":"BASE64",
        "group_id":group_id,
        "user_id":uid,
        "user_info":json.dumps(userinfo),
        "quality_control":"LOW"
    }
    
    access_token = get_access_token()
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/json'}
    response = requests.post(request_url, data=json.dumps(params), headers=headers)
    if response:
        return (response.json())
    else:
        return "Unknown Error"
        
def face_search(img64code):
    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/search"
    params = {
        "image":img64code,
        "image_type":"BASE64",
        "group_id_list":group_id,
        "quality_control":"LOW"
        }
    access_token = get_access_token()
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/json'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        return (response.json())
    else:
        return "Unknown Error"
